package com.bridgeintelligent.tag.engine.es.query;

import com.bridgeintelligent.tag.engine.api.Filter;
import com.bridgeintelligent.tag.engine.api.FilterGroup;
import com.bridgeintelligent.tag.engine.es.query.condition.BreadthFirstQueue;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;

import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by JackCheung on 2019/10/14 2:07 PM.
 */
@Slf4j
public class EsQueryBuilder {

    /**
     * filterGroup转成QueryBuilder
     *
     * @param filterGroup filterGroup
     * @return QueryBuilder
     */
    public static QueryBuilder buildFilter(FilterGroup filterGroup) {
        boolean isFilterEmpty = null == filterGroup || (CollectionUtils.isEmpty(filterGroup.getFilters()) && CollectionUtils.isEmpty(filterGroup.getChildren()));
        if (isFilterEmpty) {
            return QueryBuilders.matchAllQuery();
        }
        QueryBuilder queryBuilder = BreadthFirstQueue.transform(filterGroup);
        log.info("=====>筛选条件为：{}",queryBuilder);
        return queryBuilder;
    }

    public static QueryBuilder buildSimpleFilter(Filter filter) {
        return EsConditionBuilder.choseFilterType(filter);
    }

    /**
     * 根据fields创建客群分组集
     *
     * @param fields fields
     * @return List<AggregationBuilder>
     */
    public static List<AggregationBuilder> buildCustomerGroup(List<String> fields) {
        return new HashSet<>(fields).stream()
                                    .map(s -> AggregationBuilders.terms(s)
                                                                 .field(s)
                                                                 .size(1))
                                    .collect(Collectors.toList());
    }

    /**
     * 根据字段创建分组聚合
     *
     * @param fields fields
     * @return AggregationBuilder
     */
    public static AggregationBuilder buildIndex(List<String> fields) {
        if (CollectionUtils.isEmpty(fields)) {
            return null;
        }
        if (fields.size() == 1) {
            return AggregationBuilders.terms(fields.get(0))
                                      .field(fields.get(0));
        } else {
            return AggregationBuilders.terms(fields.get(0))
                                      .field(fields.get(0))
                                      .subAggregation(AggregationBuilders.terms(fields.get(1))
                                                                         .field(fields.get(1)));
        }
    }
}
